package org.x.common.web.mask;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;

/**
 *脱敏
 * @author 夏包包
 */
public class MaskSerializer extends JsonSerializer<String> implements ContextualSerializer {
    private MaskType maskType;
    private String module;

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        String maskedValue = applyRules(value);
        gen.writeString(maskedValue);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        Mask annotation = property.getAnnotation(Mask.class);
        if (annotation != null) {
            this.maskType = annotation.value();
            this.module = annotation.module();
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }

    private String applyRules(String value) {
        // 根据 maskType 和 module 执行脱敏逻辑
        switch (maskType) {
            case PHONE: return value.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
            case ID_CARD: return value.replaceAll("(\\d{6})\\d{8}(\\w{4})", "$1****$2");
            case EMAIL: return value.replaceAll("(\\w+)@(\\w+\\.\\w+)", "$1@****.$2");
            // ...其他策略
            default: return value;
        }
    }
}